﻿using AutoMapper;
using CSRedis;
using Qiniu.Util;
using SH.Common;
using SH.Common.CommonReturn;
using SH.Common.DataDictionary;
using SH.Customer.Application.IApplication.ICustomer;
using SH.Customer.Domain.CustomerClass;
using SH.Customer.ErrorCodeEnum;
using SH.Customer.Infrastructure.IRepository;
using SH.Customer.Infrastructure.Repository;
using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace SH.Customer.Application.Application
{
    public class CustomerApplication : BaseApplication<CustomerInfo>, ICustomerApplication
    {
        private readonly ICustomerRepository _customerRepository;


        private readonly IDicRepository _dicicRepository;

        private readonly IMapper _mapper;

        private readonly CSRedisClient _redis = new CSRedisClient(AppService.Configuration["redisIP"]);

        public CustomerApplication(ICustomerRepository customerRepository, IMapper mapper, IDicRepository dicicRepository) : base(customerRepository)
        {
            _customerRepository = customerRepository;
            _mapper = mapper;
            _dicicRepository = dicicRepository;
        }

        /// <summary>
        /// 客户信息添加
        /// </summary>
        /// <param name="customerDto"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> CustomerAdd(CustomerDto customerDto)
        {
            ApiResult<int> apiResult = new ApiResult<int>();

            var dto = _mapper.Map<CustomerInfo>(customerDto);

            dto.AddTime = DateTime.Now;

            //验证会员卡是否存在
            var tel = await _customerRepository.GetModelByConditionAsync(m => m.Tel == dto.Tel);
            if (tel != null)
            {
                apiResult.Error(ApiResult<int>.ErrorType.Request, "已有相同手机号码的会员卡，请更换手机号码！");
                return apiResult;
            }

            await _customerRepository.InsertAsync(dto);

            apiResult.Success();

            return apiResult;
        }

        /// <summary>
        /// 客户列表
        /// </summary>
        /// <param name="ctId"></param>
        /// <param name="tel"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ApiPaging<List<CustomerShowDto>> CustomerInfoList(int ctId, string? tel, int pageIndex, int pageSize)
        {
            //var result = _redis.Get<List<CustomerShowDto>>("customrer");
            string redisKey = $"customerInfoList_{ctId}_{pageIndex}_{tel}_{pageSize}";

            // 尝试从 Redis 中获取缓存数据  
            var cachedData = _redis.Get<ApiPaging<List<CustomerShowDto>>>(redisKey);
            if (cachedData != null)
            {
                // 如果 Redis 中有数据，则直接返回  
                return cachedData;
            }

            // 如果没有缓存数据，则执行数据库查询
            var query = _customerRepository.All;

            // 构建查询表达式，加入手机号查询条件
            Expression<Func<CustomerShowDto, bool>> expression = (a) =>
            (ctId <= 0 || a.CtId == ctId) && // 客户ID匹配条件
            (string.IsNullOrEmpty(tel) || a.Tel == tel); // 手机号匹配条件


            var customerQuery = query.LeftJoin<Dic>((a, b) => a.CtId == b.Id, "shmultitenantdb.dic").Select((a, b) => new CustomerShowDto
            {
                CtId = b.Id,
                CtName = b.Value,
                CId = a.CId,
                CName = a.CName,
                Tel = a.Tel,
                Tag = a.Tag,
                Birthday = a.Birthday,
                Balance = a.Balance,
                Integral = a.Integral,
                Consumption = a.Consumption,
                AccumulativeConsumption = a.AccumulativeConsumption,
                CumulativeNumber = a.CumulativeNumber,
                IsFreeze = a.IsFreeze,
                CAge = a.CAge,
                CAddress = a.CAddress,
                IdCardNumber = a.IdCardNumber,
            }).OrderByDescending(a => a.AddTime);


            int totalCount = 0;
            int pageCount = 0;
            customerQuery = customerQuery.Where(expression);
            totalCount = customerQuery.Count();
            pageCount = (int)Math.Ceiling(totalCount * 1.0 / pageSize);
            var list = customerQuery.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            ApiPaging<List<CustomerShowDto>> apiPaging = new ApiPaging<List<CustomerShowDto>>();
            apiPaging.TotalCount = totalCount;
            apiPaging.PageCount = pageCount;
            apiPaging.Data = list;

            // 将查询结果存入 Redis 缓存，设置过期时间（例如：30分钟）  
            _redis.Set(redisKey, apiPaging, TimeSpan.FromMinutes(1));

            //var dicquery = _dicicRepository.GetDics();

            return apiPaging;
        }

        /// <summary>
        /// 获取客户信息详情
        /// </summary>
        /// <param name="cId"></param>
        /// <returns></returns>
        public async Task<CustomerInfo> GetCustomerDelitalAsync(int cId)
        {
            var list = await _customerRepository.GetModelByConditionAsync(m => m.CId == cId);
            return list;
        }

        /// <summary>
        /// 获取客户类型字典列表
        /// </summary>
        /// <returns></returns>
        public List<Dic> GetCustomerTypeDicsList()
        {
            var result = _redis.Get<List<Dic>>("dictionaries");
            if (result == null || !result.Any())
            {
                result = _customerRepository.GetDics().Where(m => m.Identification == "customertype").ToList();
                var random = new Random();
                var time = random.Next(60);
                _redis.Set("dictionaries", result, time);
            }

            return result;
        }

        /// <summary>
        /// 获取国家字典列表
        /// </summary>
        /// <returns></returns>
        public List<Dic> GetNationDicsList()
        {
            var result = _redis.Get<List<Dic>>("nations");
            if (result == null || !result.Any())
            {
                result = _customerRepository.GetDics().Where(m => m.Identification == "country").ToList();
                var random = new Random();
                var time = random.Next(60);
                _redis.Set("nations", result, time);
            }
            return result;
        }

        /// <summary>
        /// 客户修改
        /// </summary>
        /// <param name="customerUpdDto"></param>
        /// <returns></returns>
        public ApiResult<int> UpdCustomer(CustomerUpdDto customerUpdDto)
        {
            ApiResult<int> apiResult = new ApiResult<int>();

            var item = _mapper.Map<CustomerInfo>(customerUpdDto);

            item.AddTime = DateTime.Now;

            var info = _customerRepository.Upd(item);

            apiResult.Success(info);

            return apiResult;
        }
    }
}
